<?php

defined('BASEPATH') OR exit('No direct script access allowed');
//---------------------------------------------------------
//|	发现模块
//---------------------------------------------------------
//| @author rable
//---------------------------------------------------------
class Find extends MY_Controller {
	
	/**
	 * 分类模型
	 * @var ConsumerFindCategoryModel
	 */
	public $mCategory;
	
	/**
	 * 发现模型
	 * @var ConsumerFindModel
	 */
	public $mFind;
	/**
	 * 模型
	 * @var ConsumerFindAttributeModel
	 */
	public $mAttribute;
	/**
	 * 模型
	 * @var ConsumerFriendsCircleModel
	 */
	public $mFriends;
	
	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerFindCategoryModel', 'mCategory', 'consumer');
		$this->loadModel('ConsumerFindModel', 'mFind', 'consumer');
		$this->loadModel('ConsumerFindAttributeModel', 'mAttribute', 'consumer');
		$this->loadModel('ConsumerFriendsCircleModel', 'mFriends', 'consumer');
	}

    /**
     * 便民服务
     */
    public function find(){
        $page	= (int)post('page');
        $sort 	= (int)post('sort'); // 1 距离最近       2 时间最新      3 浏览最高
        $county = (int)post('county');
        $categoryId = (int)post('category_id');

        $latitude	= post('latitude');
        $longitude 	= post('longitude');

        $base = array(
            'name'=>'全部',
            'icon'=>getDefaultImg(),
        );

        if ($categoryId){
            $tinfo = $this->mCategory->getInfo($categoryId);
            $base['name'] = isset($tinfo['name'])?$tinfo['name']:"";
            $base['icon'] = isset($tinfo['icon'])?$tinfo['icon']:"";
            /**
             * 是否收藏
             */
            $base['is_Collection'] = "1";//没有关注
            if ($this->userId){
                if ($this->mUser->hasCollection($this->userId, $categoryId, 3)){
                    $base['is_Collection'] = "2";//有关注
                }
            }
        }

        //获取关注总量
        $base['total_collection'] = (string)$this->mUser->getCollectionTotal($categoryId, 6);
        //获取该分类总帖子数
        $base['total_find'] = (string)$this->mFind->getFindCategoryTotal($categoryId);

        //发现列表
        $list = $this->mFind->appGetList($county,$sort,$page,0,0,$latitude,$longitude,$categoryId);
//p($list);
        $category = $this->mCategory->getList();
        if ( ! $category){
            $this->ajaxReturn(0,'数据为空');
        }
        array_unshift($category, array('id'=>0,'name'=>'全部'));
        $location = getCustomConfig('location', 'location');
        if ($county > 0){
            $county = array(
                $list[0]['province'],
                $list[0]['city'],
                $list[0]['county'],
            );
        }else{
            $county = null;
        }
        $data = array(
            'sort' => $sort,
            'county' => $county,
            'location' => $location,
            'list' => $list,
            'base' => $base,
            'category' => $category,
            'categoryId' => $categoryId,
            'title' => '便民服务'
        );
        $this->view('find/find', $data, 'layer_mobile');
    }

    /**
     * 获取发现列表
     */
    public function getFindList(){
        $page	= post('page');
        $sort 	= post('sort');
        $county = (int)post('county');
        $userId = (int)post('userId');
        $categoryId = (int)post('category_id');

        $latitude	= post('latitude');
        $longitude 	= post('longitude');
        $base = array(
            'name'=>'全部',
            'icon'=>getDefaultImg(),
        );

        if ($categoryId){
            $tInfo = $this->mCategory->getInfo($categoryId);
            $base['name'] = isset($tInfo['name']) ? $tInfo['name'] : "";
            $base['icon'] = isset($tInfo['icon']) ? $tInfo['icon'] : "";
            /**
             * 是否收藏
             */
            $base['is_Collection'] = "1";//没有关注
            if ($userId){
                if ($this->mUser->hasCollection($userId, $categoryId, 5)){
                    $base['is_Collection'] = "2";//有关注
                }
            }
        }
        //获取关注总量
        $base['total_collection'] = (string)$this->mUser->getCollectionTotal($categoryId,5);
        //获取该分类总帖子数
        $base['total_find'] = (string)$this->mFind->getFindCategoryTotal($categoryId);
        //发现列表
        $tA = $this->mFind->appGetList($county,$sort,$page,0,0,$latitude,$longitude,$categoryId);
        $data = array(
            'list' => $tA,
            'base' => $base,
        );

        $this->ajaxReturn(1,'',$data);
    }

    /**
     * 获取我发布的发现
     */
    public function index(){
        $relationId = (int)get('id');
        if (!$relationId){
            $relationId = $this->userId;
        }
        $list = $this->mFind->appGetMyList($relationId);

        $count = array(
            'find' => $list['total'],
            'friends' => $this->mFriends->getTotal($relationId),
        );

        if ($relationId == $this->userId){
            $title = '我的发布';
            $titleFriendsCircle = '我的动态';
            $user = array(
                'userPortrait' => getImage($this->userPortrait, 'xs'),
                'userName' => $this->userName,
                'userMobile' => substr($this->userMobile, 0, 3).'****'.substr($this->userMobile,-4)
            );
            $isMe = true;
        }else{
            $title = '他的发布';
            $titleFriendsCircle = '他的动态';
            $info = $this->mUser->getInfo($relationId);
            $user = array(
                'userPortrait' => is_array($info['portrait']) ? $info['portrait']['xs'] : $info['portrait'],
                'userName' => $info['nickname'],
                'userMobile' => substr($info['mobile'], 0, 3).'****'.substr($info['mobile'],-4)
            );
            $isMe = false;
        }
        $data = array(
            'isMe' => $isMe,
            'user' => $user,
            'count' => $count,
            'list' => $list['list'],
            'title' => $title,
            'relationId' => $relationId,
            'titleFriendsCircle' => $titleFriendsCircle
        );
        $this->view('find/index', $data, 'layer_mobile');
    }

    /**
     * 动态获取列表数据
     */
    public function getList(){
        $page = (int)post('page');
        $relationId = (int)post('relationId');
        if (!$relationId){
            $this->ajaxReturn(0, '数据错误');
        }
        $page += 1;
        $list = $this->mFind->appGetMyList($relationId, $page);
        $this->ajaxReturn(1, '', $list);
    }

    /**
     * 添加发布
     */
    public function add(){
        $location = getCustomConfig('location', 'location');
        $user = array(
            'userName' => $this->userName,
            'userMobile' => $this->userMobile
        );
        $category = $this->mCategory->getList();
        if ( ! $category){
            $this->appReturn(0,'数据为空');
        }
        array_unshift($category, array('id'=>0,'name'=>'全部'));
        $data = array(
            'category' => $category,
            'user' => $user,
            'location' => $location,
            'add' => true,
            'title' => '添加发布'
        );
        $this->view('find/form', $data, 'wx_validation,layer_mobile');
    }

    /**
     * 修改发布
     */
    public function edit(){
        $id = (int)get('id');
        if (!$id){
            show_404();
        }
        $info = $this->mFind->getInfo($id);
        if (!$info){
            show_404();
        }
        $location = getCustomConfig('location', 'location');
        $user = array(
            'userName' => $this->userName,
            'userMobile' => $this->userMobile
        );
        $category = $this->mCategory->getList();
        if ( ! $category){
            $this->appReturn(0,'数据为空');
        }
        array_unshift($category, array('id'=>0,'name'=>'全部'));
        $data = array(
            'info' => $this->getFindInfo($id, true),
            'category' => $category,
            'user' => $user,
            'location' => $location,
            'add' => false,
            'title' => '修改发布'
        );
        $this->view('find/form', $data, 'wx_validation,layer_mobile');
    }

    /**
     * 发布/编辑发现消息
     */
    public function saveFind(){
        //表单验证
        $vConf = array(
            array('title', '标题', 'required'),//
            array('content', '内容', 'required'),//
            array('category_id', '分类id', 'required|is_natural_no_zero'),
            array('nickname', '联系人', 'required'),
            array('mobile', '电话', 'required|valid_mobile'),
            array('county_name', '省市区名称', 'required'),
            array('address', '详细地址', 'required'),
            array('province', '省id', 'required|is_natural_no_zero'),
            array('city', '市id', 'required|is_natural_no_zero'),
            array('county', '区id', 'required|is_natural_no_zero'),
            array('latitude', '经度', 'required'),
            array('longitude', '纬度', 'required'),
        );
        $this->formDataValidation($vConf);

        $id				= trim(post('id'));//发现id
        $title			= trim(post('title'));
        $content 		= trim(post('content'));
        $categoryId 	= post('category_id');
        $nickname 		= trim(post('nickname'));
        $mobile 		= post('mobile');
        $county_name	= trim(post('county_name')); //省市区名
        $address 		= trim(post('address'));
        $province 		= post('province');
        $city 			= post('city');
        $county 		= post('county');
        $latitude		= trim(post('latitude'));
        $longitude		= trim(post('longitude'));
        $img            = post('img'); // 旧图片
        $images         = post('images'); // 图片
        $attribute  	= post('attribute');
        $tFind = array();
        if ($id){
            //验证是否存在
            $tFind = $this->mFind->getInfo($id,true);
            if (! $tFind){
                $this->ajaxReturn(0,'该信息已经不存在');
            }
        }

        if (! is_array($attribute) && $attribute){
            $this->ajaxReturn(0,'特殊属性格式错误');
        }

        //$attribute = json_decode('[{"attr_id":"1","attr_value":"aaa"},{"attr_id":"4","attr_value":"aaa"}]',true);

        if ( ! $tInfo = $this->mCategory->getInfo($categoryId)){
            $this->ajaxReturn(0,'分类不存在');
        }

        if ($tInfo['attr_cate_id'] && ! is_array($attribute)){
            $this->ajaxReturn(0,'请设置特殊属性');
        }

        $this->db->trans_begin();//开启事务

        if ($id){
            $data = array(
// 					'consumer_id'=>$this->userId,
// 					'category_id'=>$categoryId,
                'title'=>base64_encode($title),
                'content'=>base64_encode($content),
// 					'pic'=>json_encode(array()),
                'province'=>$province,
                'city'=>$city,
                'county'=>$county,
                'county_name'=>$county_name,
                'address'=>$address,
                'latitude'=>$latitude,
                'longitude'=>$longitude,
                'nickname'=>$nickname,
                'mobile'=>$mobile,
// 					'read_number'=>0,
 					'status'=>1,
// 					'addtime'=>time(),
// 					'is_delete'=>1,//未删除
            );

            $query = $this->mFind->save($data,$id);
            if (! $query){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'发布失败');
            }
        }else{

            $data = array(
                'consumer_id'=>$this->userId,
                'category_id'=>$categoryId,
                'title'=>base64_encode($title),
                'content'=>base64_encode($content),
                'pic'=>json_encode(array()),
                'province'=>$province,
                'city'=>$city,
                'county'=>$county,
                'county_name'=>$county_name,
                'address'=>$address,
                'latitude'=>$latitude,
                'longitude'=>$longitude,
                'nickname'=>$nickname,
                'mobile'=>$mobile,
                'read_number'=>0,
                'status'=>2,
                'addtime'=>time(),
                'is_delete'=>1,//未删除
            );

            $tId = $this->mFind->save($data);
            if (! $tId){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'发布失败');
            }
        }

        $tId = $id?:$tId;

        //特殊属性
        if (is_array($attribute) && !empty($attribute)){
            $tAttr = array();
            foreach ($attribute as $k=>$v){
                $tAttr[] = array(
                    'attr_id'=>$v['attr_id'],
                    'attr_value'=>$v['attr_value'],
                    'find_id'=>$tId,
                );
            }

            if ( ! $this->mAttribute->saveBatchAttribute($tAttr,$id)){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'保存失败');
            }
        }

        /**
         * 上传图片
         */
        $result = array();
        if ( ! empty($images)){
            $path = 'uploads/find/'.$this->userId.'/'.$tId.'/';
            $result = saveCSVimg($images, $path, uniqid());
            if (empty($result)) {
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '图片上传失败');
            }
        }
        if (!empty($img)){
            $result = array_merge($result, $img);
            foreach ($result as $k=>$v){
                $result[$k] = str_replace(base_url(), "", $v);
            }
        }

        //把旧图片找出来
        if ($id){
            //验证是否存在
            $tFindImgs = json_decode($tFind['pic'],true);
            //循环，查找是否还在最新的地址里面
            foreach ($tFindImgs as $k=>$v){
                if ( ! in_array($v, $result)){
                    //是否有 ? 去掉
                    if (stripos($v, '?') !== false){
                        $v = strstr($v, '?', true);
                    }

                    if (! file_exists($v)){
                        continue;
                    }
                    //获取文件名
                    $tI = explode('/', $v);
                    $filename = $tI[count($tI)-1];
                    $sm = str_replace($filename, 'sm/'.$filename, $v);
                    $xs = str_replace($filename, 'xs/'.$filename, $v);
                    //不在里面 删除
                    @unlink($v);
                    @unlink($sm);
                    @unlink($xs);
                }
            }
        }

        if ( ! $this->mFind->save(array('pic'=>json_encode($result)),$tId)){
            $this->db->trans_rollback();
            $this->ajaxReturn(0,'保存失败');
        }
        $this->db->trans_commit();

        if ( ! $id){
            $this->loadModel('ConsumerExperienceValueModel', 'mExperience','consumer');
            $this->loadModel('ConsumerMallModel', 'mMall','consumer');
            //发布时 编辑时除外
            $this->mMall->_addIntegral(4, $this->userId, $this->userIntegral);
            $this->mExperience->_addExperienceValue(3, $this->userId, $this->userExperienceValue);
            $this->ajaxReturn(1,'发布成功',null, getUrl('find/success?id'.$tId));
        }
        $this->ajaxReturn(1,'编辑成功', null, getUrl('find/success?id'.$tId));
    }

    /**
     * 移除我发布的发现
     */
    public function rmMyFind(){
        //表单验证
        $vConf = array(
            array('find_id', '发现id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('find_id' => get('find_id')));

        $findId = trim(get('find_id'));

        $tA = $this->mFind->getInfo($findId);
        if ( ! $tA){
            $this->ajaxReturn(0,'该信息不存在');
        }

        //验证用户
        if ($tA['consumer_id'] != $this->userId){
            $this->ajaxReturn(0,'你不能删除该信息');
        }

        $this->db->trans_begin();

        if ( ! $this->mFind->save(array('is_delete'=>2),$findId)){
            $this->db->trans_rollback();
            $this->ajaxReturn(0,'删除失败');
        }

        $this->db->trans_commit();
        $this->ajaxReturn(1,'删除成功', null, getUrl('find'));
    }

    /**
     * 发布详情
     */
    public function details(){
        //表单验证
        $vConf = array(
            array('find_id', '发现id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('find_id' => get('find_id')));

        $findId = (int)get('find_id');
        if (!$findId){
            show_404();
        }
        $tA = $this->mFind->getInfo($findId);
        if ( ! $tA){
            show_error('信息不存在');
        }
        $info = $this->getFindInfo($findId);
        /**
         * 是否收藏
         */
        $info['is_collection'] = "1";//没有收藏
        if ($this->userId){
            if ($this->mUser->hasCollection($this->userId, $findId, 2)){
                $info['is_collection'] = "2";//有收藏
            }
        }
        $data = array(
            'info' => $info,
            'title' => '详情',
        );
        $this->view('find/details', $data, 'layer_mobile');
    }

    /**
     * 获取特殊属性分类
     */
    public function appAttribute(){
        //表单验证
        $vConf = array(
            array('category_id', '分类', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $category_id = post('category_id');
        $tA = $this->mAttribute->getList($category_id);
        $this->ajaxReturn(1,'', $tA);
    }

    /**
     * 发布成功
     */
    public function success(){
        $id = (int)get('id');
        $data = array(
            'url' => getUrl('find/index?id='.$id),
            'title' => '发布成功',
        );
	    $this->view('common/releaseSuccess', $data);
    }

    /**
     * 评论
     */
    public function comment(){
        $findId = trim(get('find_id'));
        $findId = (int)$findId;
        if (!$findId){
            show_404();
        }
        $tA = $this->mFind->getInfo($findId);
        if ( ! $tA){
            show_error('数据不存在');
        }
        $list = $this->mFind->appGetCommentList($findId, 1);
        $data = array(
            'list' => $list,
            'find_id' => $findId,
            'title' => '评论'
        );
        $this->view('find/comment', $data, 'wx_validation,layer_mobile');
    }

    /**
     * 评论发现
     */
    public function saveComment(){
        //表单验证
        $vConf = array(
            array('find_id', '发现id', 'required|is_natural_no_zero'),
            array('content', '发现内容', 'required'),
        );

        $this->formDataValidation($vConf);

        $findId = trim(post('find_id'));
        $content = trim(post('content'));
        $comment_id = trim(post('comment_id'));

        $tA = $this->mFind->getInfo($findId);
        if ( ! $tA){
            $this->ajaxReturn(0,'数据不存在');
        }
    //获取该条信息
        $maxId = 0;
        if ($comment_id){
            $tComment = $this->mFind->getCommentInfo($comment_id);
            if ($tComment){
                $maxId = $tComment['max_parent_id'];
            }
        }
        $data = array(
            'parent_id'=>$comment_id,
            'find_id'=>$findId,
            'consumer_id'=>$this->userId,
            'content'=>base64_encode($content),
            'good'=>0,
            'addtime'=>time(),
            'max_parent_id'=>$maxId,
            'status'=>1,
        );

        if ( ! $this->mFind->saveComment($data)){
            $this->ajaxReturn(0,'评论失败');
        }

        $this->ajaxReturn(1,'评论成功', null, getUrl('find/comment?find_id='.$findId));
    }

	/**
	 * 上传图
	 */
	public function upload(){
		if ( ! $_FILES){
			$this->ajaxReturn(0,'文件不存在');
		}
		
		$tImgs = array();
		$path = 'uploads/find/temp/'.$this->userId;
		
		foreach ($_FILES as $k=>$v){
			$result = imageUpload($path, $k,uniqid().rand(0,9999),true);
			if ( ! $result['status']){
				foreach ($tImgs as $ik=>$iv){
					unlink($iv);
				}
				$this->ajaxReturn(0,'上传失败');
			}
			
			$tImgs[] = $result['data'];
		}
		
		foreach ($tImgs as $k=>&$v){
			$v = getImage($v,'og');
		}
		
		$this->ajaxReturn(1,'',$tImgs);
	}

    /**
     * 获取发现详情
     * @param $findId       int         发现id
     * @param $attribute    bool        true: 只获取详情和特殊值  false：获取全部
     * @return array
     */
	public function getFindInfo($findId, $attribute = false){
		$tA = $this->mFind->getInfo($findId);
		$tUser = array();
		$sessionid = $this->sessionId;
		if ($sessionid){
			$tUser = $this->mUser->getInfoBySessionid($sessionid);
		}
		if ($tA){
            //获取特殊值
            $tA['attr'] = $this->mAttribute->getAttributeValueList($findId);
            unset($tA['status']);
            unset($tA['name']);
            if ($attribute){
                return $tA;
            }

			$tA['is_approval'] = "1";
			if ($tUser && $this->mFind->hasApproval($findId, $this->userId)){
				$tA['is_approval'] = "2";
			}
			
			$tA['is_collection'] = "1";
			if ($tUser && $this->mUser->hasCollection($this->userId,$findId,2)){
				$tA['is_collection'] = "2";
			}
            $tA['mobile_og'] = $tA['mobile'];
            $tA['mobile'] = substr($tA['mobile'], 0,3).'****'.substr($tA['mobile'], -4);
//			if ( ! $tUser){
//                $tA['mobile'] = substr($tA['mobile'], 0,3).'****'.substr($tA['mobile'], -4);
//			}
		
			//获取推荐
			$total = $this->mFind->getFindTotal($tA['consumer_id']);
			$tA['desc'] = '最近发布了'.$total.'条';
			
			//获取推荐
//			$tA['relevance'] = $this->mFind->appGetList(0,3,1,5);//获取浏览最多，第1页
//			$tConsumer = array();
//			if ($tA['relevance']){
//				$tConsumerIds = array();
//				foreach ($tA['relevance'] as $k=>$v){
//					if ( ! in_array($v['consumer_id'], $tConsumerIds)){
//						$tConsumerIds[] = $v['consumer_id'];
//					}
//				}
//
//				if ($tConsumerIds){
//					$this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
//					$tConsumer = $this->mConsumer->getInfoByIds($tConsumerIds);
//				}
//			}
//
//			//数据
//			foreach ($tA['relevance'] as $k=>$v){
//				$tA['relevance'][$k]['nickname'] = isset($tConsumer[$v['consumer_id']]) ? $tConsumer[$v['consumer_id']]['nickname'] : '';
//				$tA['relevance'][$k]['portrait'] = isset($tConsumer[$v['consumer_id']]) ? $tConsumer[$v['consumer_id']]['portrait']['xs'] : '';
//			}
		}
		
		//浏览记录
		
		//是否浏览
		if ( $tUser && ! $this->mFind->hasApproval($findId, $this->userId,2)){
			//浏览记录保存
			$save = true;
			$this->db->trans_begin();
			//点赞数+1
			if ( ! $this->mFind->save(array('read_number' => $tA['read_number'] + 1),$findId)){
				$this->db->trans_rollback();
				$save = false;
			}
			
			$data = array(
					'consumer_id'=>$this->userId,
					'find_id'=>$findId,
					'is_view'=>2,
					'addtime'=>time(),
			);
			
			if ( ! $this->mFind->saveApproval($data)){
				$this->db->trans_rollback();
				$save = false;
			}
			
			if ($save){
				$this->db->trans_commit();
			}
		}
		
		//评论列表
		$tA['comment'] = $this->mFind->appGetCommentList($findId,1,2);
		
		return $tA;
	}

    /**
     * 评论列表
     */
	public function getCommentList(){
		//表单验证
		$vConf = array(
				array('find_id', '发现id', 'required|is_natural_no_zero'),
		);
		
		$this->formDataValidation($vConf);
		
		$findId = trim(post('find_id'));
		$page = trim(post('page'));

		$tA = $this->mFind->appGetCommentList($findId,$page);
		if ( ! $tA){
			$this->ajaxReturn(1,'没有评论');
		}
		$this->ajaxReturn(1,'',$tA);
	}

    /**
     * 给发现点赞
     */
    public function approval(){
        //表单验证
        $vConf = array(
            array('find_id', '发现id', 'required|is_natural_no_zero'),
        );

        $this->formDataValidation($vConf);

        $findId = trim(post('find_id'));

        $tA = $this->mFind->getInfo($findId);
        if ( ! $tA){
            $this->ajaxReturn(0,'点赞失败');
        }

        //已经点过
        $this->db->trans_begin();
        if ($this->mFind->hasApproval($findId, $this->userId)){
            //$this->ajaxReturn(0,'已经点过赞');
            //点赞数-1
            if ( ! $this->mFind->save(array('approval' => $tA['approval'] - 1),$findId)){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'点赞失败');
            }

            //点赞记录保存
            if ( !$this->mFind->saveApproval(array('is_approval'=>NULL),$findId,$this->userId)){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'点赞失败');
            }

            $this->db->trans_commit();
            $data = array(
                'is_approval'=>"1",
                'approval' => $tA['approval'] - 1
            );
            $this->ajaxReturn(1,'取消成功', $data);
        }else{

            //点赞数+1
            if ( ! $this->mFind->save(array('approval' => $tA['approval'] + 1),$findId)){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'点赞失败');
            }

            //点赞记录保存
            if ( !$this->mFind->saveApproval(array('is_approval'=>2),$findId,$this->userId)){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'点赞失败');
            }
            $this->db->trans_commit();
            $data = array(
                'is_approval'=>"2",
                'approval' => $tA['approval'] + 1
            );
            $this->ajaxReturn(1,'点赞成功', $data);
        }

    }
}
	